package com.ling.web.video.extractor.utils;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 全局单例线程池
 */
public class ThreadPoolUtil {
    private static ThreadPoolExecutor instanceExecutor;
    private static Handler mainHandle;

    /**
     * 返回线程
     */
    private static void initExecutor() {
        int corePoolSize = 2;//保留在池中的线程数，即空闲状态
        int maximumPoolSize = 4;//最大线程池数量
        long keepAliveTime = 6;//当线程数大于核心时，这是多余的空闲线程在终止之前等待新任务的最长时间。
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingDeque<>(100);
        ThreadFactory threadFactory = new NameTreadFactory();
        RejectedExecutionHandler handler = new IgnorePolicy();
        instanceExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
        instanceExecutor.prestartAllCoreThreads(); // 预启动所有核心线程
        //主线程
        if(mainHandle != null){
            mainHandle.removeCallbacksAndMessages(null);
        }
        Log.d("ThreadPoolHelper", "new sExecutor");
    }

    public static synchronized ThreadPoolExecutor generateExecutor() {
        //当线程池执行了shutdownNow shutdown getPoolSize()值为0
        if (instanceExecutor == null || instanceExecutor.getPoolSize() == 0) initExecutor();
        return instanceExecutor;
    }

    public static boolean isOnMainThread(){
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    public static synchronized void runOnMainThread(Runnable mRun) {
        //主线程
        if(isOnMainThread()){
            mRun.run()
        }else{
            if(mainHandle == null){
                mainHandle = new Handler(Looper.getMainLooper());
            }
            mainHandle.post(runnable);
        }
    }

    static class NameTreadFactory implements ThreadFactory {
        //原子计数器 多个线程同时使用会用到AtomicInteger
        private final AtomicInteger mThreadNum = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "my-thread-" + mThreadNum.getAndIncrement());
            Log.d("ThreadHelper", t.getName() + " has been created");
            return t;
        }
    }

    static class IgnorePolicy implements RejectedExecutionHandler {

        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            doLog(r, e);
        }

        private void doLog(Runnable r, ThreadPoolExecutor e) {
            // 可做日志记录等
            Log.e("ThreadHelper", r.toString() + " rejected");
        }
    }
}